package cn.itcast.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

//特点：与webservlet相反。此处，ZuulFilter放行不做反应。而webservlet中放行要do.filter();
@Component//加入容器，随时调用
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //过滤的类型、pre
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //设置过滤的执行时机
        return FilterConstants.DEBUG_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {//动态过滤
        //动态加入拦截条件，ru如果传进来消防员不开启拦截
        //获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String xfy = request.getParameter("xfy");
        if (!StringUtils.isBlank(xfy)){
            //消防员进来，不开启拦截
            return false;//不拦截，响应
        }
        //开启过滤
        return true;
    }

    @Override//拦截处理业务逻辑
    public Object run() throws ZuulException {
        //判断是否参数存在username，存在则放行
        //看源码获取request方法，进而得到参数，判断
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String username = request.getParameter("username");
        if (StringUtils.isBlank(username)){
            //为空禁止登入
            ctx.setSendZuulResponse(false);//false拦截,true不拦截
            ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());//设置状态码；
        }
        return null;//默认放行。
    }
}
